package com.sanq.product.books.controller;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.config.Tables;
import com.sanq.product.books.entity.VisiLog;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.date.LocalDateUtils;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.GlobalUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.config.utils.web.UserAgentUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.annotation.Security;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/app/visi_log")
public class VisiLogController {

    @Resource
    private JedisPoolService jedisPoolService;

    @Security
    @LogAnnotation(description = "保存访问信息")
    @PostMapping(value = "/save")
    public Response update(HttpServletRequest request, @RequestBody VisiLog visiLog) {
        String visiLogKey = Redis.ReplaceKey.getVisiLogKey(LocalDateUtils.nowTime());

        visiLog.setId(jedisPoolService.incr(Tables.visiLog.getTable()) + LocalDateUtils.nowTime().getTime());
        //访问时间
        visiLog.setDay(LocalDateUtils.nowTimeStr());

        //访问者IP
        visiLog.setIp(GlobalUtil.getIpAddr(request));

        // 访问Agent
        String userAgent = request.getHeader("User-Agent");
        visiLog.setUserAgent(userAgent);

        try {
            visiLog.setOs(UserAgentUtil.getOs(userAgent));
        } catch (IOException e) {
            visiLog.setOs("未知设备");
        }

        jedisPoolService.putList(visiLogKey, JsonUtil.obj2Json(visiLog));

        return new Response().success();
    }
}
